package com.gwtapps.serialization.client;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.GWT;


public class Serializer
{
	private static Map SERIALIZABLE_TYPES;
	private static Map serializableTypes(){
		if( SERIALIZABLE_TYPES == null ){
			SERIALIZABLE_TYPES = new HashMap();
		}
		return SERIALIZABLE_TYPES;
	}
	protected void addObjectSerializer( String name, ObjectSerializer obj ){
		serializableTypes().put( name.toLowerCase(), obj );
	}	  
	protected ObjectSerializer getObjectSerializer( String name ){
		return (ObjectSerializer)serializableTypes().get( name );
	}	
	protected Serializer(){
		
	}
	
	static protected String getTypeName( Serializable obj ){
		String typeName = GWT.getTypeName( obj );
		typeName = typeName.substring(typeName.lastIndexOf('.')+1);
		return typeName.toLowerCase();
	}

	public void serializeToDocumentObject( Serializable obj, DocumentObject document ) {
		String name = getTypeName( obj );
		ObjectSerializer serializer = getObjectSerializer( name );
		if( serializer == null ){
			throw new SerializationException("Can't find object serializer for "+name);
		}
		document.setName( name );
		serializer.serialize( obj, document );
	}

	public Serializable deserializeFromDocumentObject( DocumentObject document ) throws SerializationException{	
		String name = document.getName();
		ObjectSerializer serializer = getObjectSerializer( name );
		if( serializer == null ){
			throw new SerializationException("Can't find object serializer for "+name);
		}
		return serializer.deserialize( document );		
	}	
}
